package com.tensquare.friend.service;

import com.tensquare.friend.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Administrator on 2021/6/21.
 */
@Service
public class FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    /**
     * 添加好友
     * @param userId
     * @param friendid
     */
    @Transactional
    public int addFriend(String userId, String friendid) {
        //查询是否已添加过好友
        Friend friend = friendDao.findByUseridAndFriendid(userId, friendid);
        if (friend != null){
            //说明已添加了好友
            return 0;
        }
        //直接添加好友
        friend = new Friend();
        friend.setUserid(userId);
        friend.setFriendid(friendid);
        friend.setIslike("0");  //单向喜欢
        friendDao.save(friend);
        //更新双方的互相关注
        friend = friendDao.findByUseridAndFriendid(friendid,userId);
        if (friend != null){
            friendDao.updateIslike("1",userId,friendid);
            friendDao.updateIslike("1",friendid,userId);
        }
        return 1;
    }

    public int addNoFriend(String userId, String friendid) {
        NoFriend noFriend = noFriendDao.findByUseridAndFriendid(userId, friendid);
        if (noFriend != null){
            //说明已添加非好友
            return 0;
        }
        //添加非好友
        noFriend = new NoFriend();
        noFriend.setUserid(userId);
        noFriend.setFriendid(friendid);
        noFriendDao.save(noFriend);
        return 1;
    }

    @Transactional
    public void deleteFriend(String userId, String friendid) {
        //删除表中userid到friendid的数据
        friendDao.deleteFriend(userId,friendid);
        //更新表中数据friendid到userid中的islike为0
        friendDao.updateIslike("0",friendid,userId);
        //非好友添加数据
        addNoFriend(userId,friendid);


    }
}
